<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Category extends CI_Controller {

    function __construct(){
        parent::__construct();
        $this->load->model('product/product_model');
        $this->load->model('category_model');
    }

    function index(){
        $data['result'] = $this->product_model->get_category();
        $data['tpl'] = 'admin/category/index';
        $this->load->view('_layout/admin', $data);
    }

    function update($category_id = 0){
        $category_id = intval($category_id);

        if ($_POST){
            $info = array(
                'title'        => trim($this->input->post('title')),
                'discount'     => floatval($this->input->post('discount')),
                'parent_id'    => intval($this->input->post('parent_id')),
                'intro'        => trim($this->input->post('intro')),
                'update_date'  => date('Y-m-d H:i:s')
            );

            if ($category_id != 0){
                $info['category_id'] = $category_id;
                $info['update_date'] = date('Y-m-d H:i:s');
            } else {
                $info['active_flag'] = ACTIVE_FLAG;
                $info['delete_flag'] = UNDELETE_FLAG;
                $info['create_date'] = date('Y-m-d H:i:s');
            }


            $result = $this->product_model->update_category($info);
            if (!is_bool($result)){
                $data['msg'] = 'Lưu danh mục thành công';
            }
        }

        if ($category_id != 0) {
            $data['data'] = $this->product_model->get_category($category_id);
        }

        $category_data = $this->product_model->get_category(0, 0);
        $category[0] = '--- Chá»�n danh má»¥c ---';
        foreach ($category_data as $key => $value){
            if ($category_id != $value['category_id']) {
                $category[$value['category_id']] = $value['title'];
            }
        }

        $data['category'] = $category;
        $data['tpl']      = 'category/edit';
        $this->load->view('_layout/admin', $data);
    }

    function delete(){
        $id = $this->input->post('id');
        if (!is_array($id)){
            $id = array($id);
        }
        $result = $this->product_model->_delete_category($id);
        echo $result;
    }

    function discount_all(){
        if ($_POST){
            $discount = floatval($this->input->post('discount'));
            $result = $this->category_model->update_all(array('discount' => $discount));
            echo $result;
        }
    }
}